package com.cdinternationalcompany.syhapp.push.xiaomi

//import com.google.gson.Gson
import android.R
import android.content.Context
import android.util.Log
import com.cdinternationalcompany.syhapp.MainActivity
import com.cdinternationalcompany.syhapp.push.NotificationHelper
import com.cdinternationalcompany.syhapp.utils.ChannelManager
import com.google.gson.Gson
import com.xiaomi.mipush.sdk.MiPushClient
import com.xiaomi.mipush.sdk.MiPushCommandMessage
import com.xiaomi.mipush.sdk.MiPushMessage
import com.xiaomi.mipush.sdk.PushMessageReceiver
import org.json.JSONObject


class XiaoMiPushMessageReceiver : PushMessageReceiver() {

    companion object {
        private val TAG = "Push.SDK.MiPushReceiver"
    }

    override fun onReceivePassThroughMessage(ctx: Context?, message: MiPushMessage?) {
        super.onReceivePassThroughMessage(ctx, message)
        Log.d(TAG,"onReceivePassThroughMessage-> ${message?.content}")
        try {
            val json = JSONObject(message?.content!!)
            val title = json.getString("title")
            val content = json.getString("content")
            val url = json.getString("url")
            NotificationHelper.showNotification(
                ctx,
                title,
                content,
                json.toString()
            )
        } catch (e: Exception) {
            Log.d(TAG, "onReceivePassThroughMessage -> ${message?.content}")
        }
    }

    override fun onCommandResult(context: Context, message: MiPushCommandMessage) {
        Log.v(
            TAG,
            "onCommandResult is called. $message"
        )

    }

    override fun onNotificationMessageClicked(ctx: Context?, message: MiPushMessage?) {
        super.onNotificationMessageClicked(ctx, message)
        try {
            val json = JSONObject(message?.content!!)
            val para = mutableMapOf<String,String>()
            for (key in json.keys()) {
                val content = json.getString(key)
                para[key] = content.toString()
                Log.i(XiaoMiPushMessageReceiver.TAG, "receive data from push, key = $key, content = $content")
            }
            ChannelManager.instance.callFlutter(
                    "PushApi/receiveMessage", para,
            )
        } catch (e: Exception) {

            Log.d(TAG, "onNotificationMessageClicked -> ${message?.content}")
        }
    }

    override fun onReceiveRegisterResult(ctx: Context?, message: MiPushCommandMessage?) {
        super.onReceiveRegisterResult(ctx, message)

        Log.i(TAG, "XiaoMiPushMessageReceiver#onReceiveRegisterResult -> ${Gson().toJson(message)}")
    }

}